#include "ngx_ngim_http.h"
#include "ngx_ngim_curl.h"
#include "ngx_ngim_http_module.h"



static ngx_int_t
ngx_ngim_http_alloc_large_header_buffer(ngx_http_request_t *r,  ngx_uint_t request_line);
static ssize_t
ngx_ngim_http_read_request_header(ngx_http_request_t *r,ngx_msec_t client_header_timeout);

static void
ngx_ngim_http_process_request_line(ngx_event_t *rev);
static void
ngx_ngim_http_process_request_headers(ngx_event_t *rev);
static void
ngx_ngim_http_test_reading(ngx_event_t *rev);



ngx_uint_t 
ngx_ngim_http_send_header(ngx_http_request_t *r)
{
    if (r->err_status) {
        r->headers_out.status = r->err_status;
        r->headers_out.status_line.len = 0;
    }
    
    return ngx_ngim_http_top_header_filter(r);
}


void
ngx_ngim_http_init_request(ngx_event_t *rev)
{
    ngx_time_t                 *tp;
    ngx_connection_t           *c;
    ngx_http_request_t         *r;
#if (NGX_HAVE_INET6)
    struct sockaddr_in6        *sin6;
    ngx_http_in6_addr_t        *addr6;
#endif
    ngx_ngim_session_t         *s;

#if (NGX_STAT_STUB)
    (void) ngx_atomic_fetch_add(ngx_stat_reading, -1);
#endif

    c = rev->data;
    s = c->data;

    if (c->destroyed) {
        return;
    }

    if (rev->timedout) {
        ngx_log_error(NGX_LOG_INFO, c->log, NGX_ETIMEDOUT, 
                      "client timed out");

        ngx_ngim_finalize_session(s);
        return;
    }

    c->requests++;

    /*hc = c->data;

    if (hc == NULL) {
        hc = ngx_pcalloc(c->pool, sizeof(ngx_http_connection_t));
        if (hc == NULL) {
            //ngx_http_close_connection(c);
            ngx_ngim_finalize_session(s);
            return;
        }
    }

    r = hc->request;

    if (r) {
        ngx_memzero(r, sizeof(ngx_http_request_t));

        r->pipeline = hc->pipeline;

        r->content_length_n = -1;

        if (hc->nbusy) {
            r->header_in = hc->busy[0];
        }

    } else {*/
    r = ngx_pcalloc(c->pool, sizeof(ngx_http_request_t));
    if (r == NULL) {
        ngx_log_error(NGX_LOG_INFO, c->log, NGX_ETIMEDOUT, 
                      "create ngx_http_request_t failed");
        ngx_ngim_finalize_session(s);
        return;
    }

    r->content_length_n = -1;

       // hc->request = r;
    //}

    s->request = r;
    c->sent = 0;
    r->signature = NGX_NGIM_MODULE;

    r->connection = c;

    rev->handler = ngx_ngim_http_process_request_line;
    r->read_event_handler = ngx_http_block_reading;

    if (c->buffer == NULL) {
        c->buffer = ngx_create_temp_buf(c->pool,
                                        1024);  //cscf->client_header_buffer_size);
        if (c->buffer == NULL) {
            ngx_ngim_finalize_session(s);
            return;
        }
    }

    if (r->header_in == NULL) {
        r->header_in = c->buffer;
    }

#if 0
    r->pool = ngx_create_pool(4096, c->log);
    if (r->pool == NULL) {
        ngx_ngim_finalize_session(s);
        return;
    }
#endif

    r->pool  = c->pool;

    if (ngx_list_init(&r->headers_out.headers, r->pool, 20,
                      sizeof(ngx_table_elt_t))
        != NGX_OK)
    {
        ngx_ngim_finalize_session(s);
        return;
    }

    /*
    r->ctx = ngx_pcalloc(r->pool, sizeof(void *) * ngx_http_max_module);
    if (r->ctx == NULL) {
        ngx_ngim_finalize_session(s);
        return;
    }

    cmcf = ngx_http_get_module_main_conf(r, ngx_http_core_module);
    r->variables = ngx_pcalloc(r->pool, cmcf->variables.nelts
                                        * sizeof(ngx_http_variable_value_t));
    if (r->variables == NULL) {
        ngx_http_close_connection(c);
        return;
    }*/

    c->single_connection = 1;
    c->destroyed = 0;

    r->main = r;
    r->count = 1;

    tp = ngx_timeofday();
    r->start_sec = tp->sec;
    r->start_msec = tp->msec;

    r->method = NGX_HTTP_UNKNOWN;

    r->headers_in.content_length_n = -1;
    r->headers_in.keep_alive_n = -1;
    r->headers_out.content_length_n = -1;
    r->headers_out.last_modified_time = -1;

    r->uri_changes = NGX_HTTP_MAX_URI_CHANGES + 1;
    r->subrequests = NGX_HTTP_MAX_SUBREQUESTS + 1;

    r->http_state = NGX_HTTP_READING_REQUEST_STATE;

    //ctx = c->log->data;
    //ctx->request = r;
    //ctx->current_request = r;
    //r->log_handler = ngx_http_log_error_handler;

#if (NGX_STAT_STUB)
    (void) ngx_atomic_fetch_add(ngx_stat_reading, 1);
    r->stat_reading = 1;
    (void) ngx_atomic_fetch_add(ngx_stat_requests, 1);
#endif

    rev->handler(rev);
}



#if 0
static ngx_int_t
ngx_ngim_http_read_discarded_request_body(ngx_http_request_t *r)
{
    size_t   size;
    ssize_t  n;
    u_char   buffer[NGX_HTTP_DISCARD_BUFFER_SIZE];

    ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                   "ngim http read discarded body");

    for ( ;; ) {

        if (!r->connection->read->ready) {
            return NGX_AGAIN;
        }

        n = r->connection->recv(r->connection, buffer, NGX_HTTP_DISCARD_BUFFER_SIZE);

        if (n == NGX_ERROR) {
            r->connection->error = 1;
            return NGX_OK;
        }

        if (n == NGX_AGAIN) {
            return NGX_AGAIN;
        }

        if (n == 0) {
            return NGX_OK;
        }
    }
}
#endif


static ngx_int_t
ngx_ngim_http_alloc_large_header_buffer(ngx_http_request_t *r,
    ngx_uint_t request_line)
{
    u_char                    *old, *new;
    ngx_buf_t                 *b;
    ngx_http_connection_t     *hc;

    ngx_log_debug0(NGX_LOG_DEBUG_NGIM, r->connection->log, 0,
                   "http alloc large header buffer");

    if (request_line && r->state == 0) {

        /* the client fills up the buffer with "\r\n" */

        r->request_length += r->header_in->end - r->header_in->start;

        r->header_in->pos = r->header_in->start;
        r->header_in->last = r->header_in->start;

        return NGX_OK;
    }

    old = request_line ? r->request_start : r->header_name_start;


    if (r->state != 0
        && (size_t) (r->header_in->pos - old)
                                     >= 8192) //cscf->large_client_header_buffers.size)
    {
        return NGX_DECLINED;
    }

    hc = r->http_connection;

    if (hc->nfree) {
        b = hc->free[--hc->nfree];

        ngx_log_debug2(NGX_LOG_DEBUG_NGIM, r->connection->log, 0,
                       "http large header free: %p %uz",
                       b->pos, b->end - b->last);

    } else if (hc->nbusy < 4 ){ //cscf->large_client_header_buffers.num) 

        if (hc->busy == NULL) {
            hc->busy = ngx_palloc(r->connection->pool,
                                  4 * sizeof(ngx_buf_t *));
            if (hc->busy == NULL) {
                return NGX_ERROR;
            }
        }

        b = ngx_create_temp_buf(r->connection->pool, 8192);
                                //cscf->large_client_header_buffers.size);
        if (b == NULL) {
            return NGX_ERROR;
        }

        ngx_log_debug2(NGX_LOG_DEBUG_NGIM, r->connection->log, 0,
                       "http large header alloc: %p %uz",
                       b->pos, b->end - b->last);

    } else {
        return NGX_DECLINED;
    }

    hc->busy[hc->nbusy++] = b;

    if (r->state == 0) {
        /*
         * r->state == 0 means that a header line was parsed successfully
         * and we do not need to copy incomplete header line and
         * to relocate the parser header pointers
         */

        r->request_length += r->header_in->end - r->header_in->start;

        r->header_in = b;

        return NGX_OK;
    }

    ngx_log_debug1(NGX_LOG_DEBUG_NGIM, r->connection->log, 0,
                   "http large header copy: %d", r->header_in->pos - old);

    r->request_length += old - r->header_in->start;

    new = b->start;

    ngx_memcpy(new, old, r->header_in->pos - old);

    b->pos = new + (r->header_in->pos - old);
    b->last = new + (r->header_in->pos - old);

    if (request_line) {
        r->request_start = new;

        if (r->request_end) {
            r->request_end = new + (r->request_end - old);
        }

        r->method_end = new + (r->method_end - old);

        r->uri_start = new + (r->uri_start - old);
        r->uri_end = new + (r->uri_end - old);

        if (r->schema_start) {
            r->schema_start = new + (r->schema_start - old);
            r->schema_end = new + (r->schema_end - old);
        }

        if (r->host_start) {
            r->host_start = new + (r->host_start - old);
            if (r->host_end) {
                r->host_end = new + (r->host_end - old);
            }
        }

        if (r->port_start) {
            r->port_start = new + (r->port_start - old);
            r->port_end = new + (r->port_end - old);
        }

        if (r->uri_ext) {
            r->uri_ext = new + (r->uri_ext - old);
        }

        if (r->args_start) {
            r->args_start = new + (r->args_start - old);
        }

        if (r->http_protocol.data) {
            r->http_protocol.data = new + (r->http_protocol.data - old);
        }

    } else {
        r->header_name_start = new;
        r->header_name_end = new + (r->header_name_end - old);
        r->header_start = new + (r->header_start - old);
        r->header_end = new + (r->header_end - old);
    }

    r->header_in = b;

    return NGX_OK;
}




static ssize_t
ngx_ngim_http_read_request_header(ngx_http_request_t *r,ngx_msec_t client_header_timeout)
{
    ssize_t                    n;
    ngx_event_t               *rev;
    ngx_connection_t          *c;
    ngx_ngim_session_t        *s;

    c = r->connection;
    rev = c->read;
    s   = c->data;

    n = r->header_in->last - r->header_in->pos;

    if (n > 0) {
        return n;
    }

    if (rev->ready) {
        n = c->recv(c, r->header_in->last,
                    r->header_in->end - r->header_in->last);
    } else {
        n = NGX_AGAIN;
    }

    if (n == NGX_AGAIN) {
        if (!rev->timer_set) {
            ngx_add_timer(rev, client_header_timeout);
        }

        if (ngx_handle_read_event(rev, 0) != NGX_OK) {
            ngx_ngim_finalize_session(s);
            return NGX_ERROR;
        }

        return NGX_AGAIN;
    }

    if (n == 0) {
        ngx_log_error(NGX_LOG_INFO, c->log, 0,
                      "client prematurely closed connection");
    }

    if (n == 0 || n == NGX_ERROR) {
        c->error = 1;
        c->log->action = "reading client request headers";

        ngx_ngim_finalize_session(s);
        return NGX_ERROR;
    }

    r->header_in->last += n;

    return n;
}


static void
ngx_ngim_http_process_request_line(ngx_event_t *rev)
{
    ssize_t                    n;
    ngx_int_t                  rc, rv;
    ngx_connection_t          *c;
    ngx_http_request_t        *r;
    ngx_ngim_session_t        *s;

    c = rev->data;
    s = c->data;
    r   = s->request;

    //create request

    ngx_log_debug0(NGX_LOG_DEBUG_NGIM, rev->log, 0,
                   "ngim http process request line");
   
    if (c->destroyed) {
        return;
    } 

    if (rev->timedout) {
        ngx_log_error(NGX_LOG_INFO, c->log, NGX_ETIMEDOUT, 
                     "ngim client timed out");
        c->timedout = 1;
        ngx_ngim_finalize_session(s);
        return;
    }


    if (rev->timer_set) {
       ngx_del_timer(rev);
    }

    rc = NGX_AGAIN;

    for ( ;; ) {

        if (rc == NGX_AGAIN) {
            n = ngx_ngim_http_read_request_header(r,500);

            if (n == NGX_AGAIN || n == NGX_ERROR) {
                return;
            }
        }

        rc = ngx_http_parse_request_line(r, r->header_in);

        if (rc == NGX_OK) {

            /* the request line has been parsed successfully */

            r->request_line.len = r->request_end - r->request_start;
            r->request_line.data = r->request_start;


            if (r->args_start) {
                r->uri.len = r->args_start - 1 - r->uri_start;
            } else {
                r->uri.len = r->uri_end - r->uri_start;
            }


            if (r->complex_uri || r->quoted_uri) {

                r->uri.data = ngx_pnalloc(r->pool, r->uri.len + 1);
                if (r->uri.data == NULL) {
                    ngx_ngim_finalize_session(s);
                    return;
                }

                rc = ngx_http_parse_complex_uri(r, 1);

                if (rc == NGX_HTTP_PARSE_INVALID_REQUEST) {
                    ngx_log_error(NGX_LOG_INFO, c->log, 0,
                                  "client sent invalid request");
                    ngx_ngim_finalize_session(s);
                    return;
                }

            } else {
                r->uri.data = r->uri_start;
            }


            r->unparsed_uri.len = r->uri_end - r->uri_start;
            r->unparsed_uri.data = r->uri_start;

            r->valid_unparsed_uri = r->space_in_uri ? 0 : 1;

            r->method_name.len = r->method_end - r->request_start + 1;
            r->method_name.data = r->request_line.data;


            if (r->http_protocol.data) {
                r->http_protocol.len = r->request_end - r->http_protocol.data;
            }


            if (r->uri_ext) {
                if (r->args_start) {
                    r->exten.len = r->args_start - 1 - r->uri_ext;
                } else {
                    r->exten.len = r->uri_end - r->uri_ext;
                }

                r->exten.data = r->uri_ext;
            }


            if (r->args_start && r->uri_end > r->args_start) {
                r->args.len = r->uri_end - r->args_start;
                r->args.data = r->args_start;
            }

#if (NGX_WIN32)
            {
            u_char  *p, *last;

            p = r->uri.data;
            last = r->uri.data + r->uri.len;

            while (p < last) {

                if (*p++ == ':') {

                    /*
                     * this check covers "::$data", "::$index_allocation" and
                     * ":$i30:$index_allocation"
                     */

                    if (p < last && *p == '$') {
                        ngx_log_error(NGX_LOG_INFO, c->log, 0,
                                      "client sent unsafe win32 URI");
                        //ngx_ngim_http_finalize_request(r, NGX_HTTP_BAD_REQUEST);
                        ngx_ngim_finalize_session(s);
                        return;
                    }
                }
            }

            p = r->uri.data + r->uri.len - 1;

            while (p > r->uri.data) {

                if (*p == ' ') {
                    p--;
                    continue;
                }

                if (*p == '.') {
                    p--;
                    continue;
                }

                break;
            }

            if (p != r->uri.data + r->uri.len - 1) {
                r->uri.len = p + 1 - r->uri.data;
                ngx_ngim_http_set_exten(r);
            }

            }
#endif

            ngx_log_debug1(NGX_LOG_DEBUG_NGIM, c->log, 0,
                           "http request line: \"%V\"", &r->request_line);

            ngx_log_debug1(NGX_LOG_DEBUG_NGIM, c->log, 0,
                           "http uri: \"%V\"", &r->uri);

            ngx_log_debug1(NGX_LOG_DEBUG_NGIM, c->log, 0,
                           "http args: \"%V\"", &r->args);

            ngx_log_debug1(NGX_LOG_DEBUG_NGIM, c->log, 0,
                           "http exten: \"%V\"", &r->exten);

            /*if (r->host_start && r->host_end) {

                host = r->host_start;
                n = ngx_http_validate_host(r, &host,
                                           r->host_end - r->host_start, 0);

                if (n == 0) {
                    ngx_log_error(NGX_LOG_INFO, c->log, 0,
                                  "client sent invalid host in request line");
                    //ngx_ngim_http_finalize_request(r, NGX_HTTP_BAD_REQUEST);
                    ngx_ngim_finalize_session(s);
                    return;
                }

                if (n < 0) {
                    //ngx_ngim_http_close_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
                    ngx_ngim_finalize_session(s);
                    return;
                }

                r->headers_in.server.len = n;
                r->headers_in.server.data = host;
            }*/

            /*if (r->http_version < NGX_HTTP_VERSION_10) {

                if (ngx_http_find_virtual_server(r, r->headers_in.server.data,
                                                 r->headers_in.server.len)
                    == NGX_ERROR)
                {
                    //ngx_ngim_http_close_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
                    ngx_ngim_finalize_session(s);
                    return;
                }

                ngx_ngim_http_process_request(r);
                return;
            }*/


            if (ngx_list_init(&r->headers_in.headers, r->pool, 20,
                              sizeof(ngx_table_elt_t))
                != NGX_OK)
            {
                ngx_ngim_finalize_session(s);
                return;
            }


            if (ngx_array_init(&r->headers_in.cookies, r->pool, 2,
                               sizeof(ngx_table_elt_t *))
                != NGX_OK)
            {
                ngx_ngim_finalize_session(s);
                return;
            }

            c->log->action = "reading client request headers";

            rev->handler = ngx_ngim_http_process_request_headers;
            ngx_ngim_http_process_request_headers(rev);

            return;
        }

        if (rc != NGX_AGAIN) {

            /* there was error while a request line parsing */

            ngx_log_error(NGX_LOG_INFO, c->log, 0,
                          "client sent invalid request");
            ngx_ngim_finalize_session(s);
            return;
        }

        /* NGX_AGAIN: a request line parsing is still incomplete */

        if (r->header_in->pos == r->header_in->end) {

            rv = ngx_ngim_http_alloc_large_header_buffer(r, 1);

            if (rv == NGX_ERROR) {
                ngx_ngim_finalize_session(s);
                return;
            }

            if (rv == NGX_DECLINED) {
                r->request_line.len = r->header_in->end - r->request_start;
                r->request_line.data = r->request_start;

                ngx_log_error(NGX_LOG_INFO, c->log, 0,
                              "client sent too long URI");
                ngx_ngim_finalize_session(s);
                return;
            }
        }
    }
}


static void
ngx_ngim_http_process_request_headers(ngx_event_t *rev)
{
    u_char                     *p;
    size_t                      len;
    ssize_t                     n;
    ngx_int_t                   rc, rv;
    ngx_table_elt_t            *h;
    ngx_connection_t           *c;
    ngx_http_request_t         *r;
    ngx_ngim_session_t         *s;

    c = rev->data;
    s = c->data;
    r = s->request;

    ngx_log_debug0(NGX_LOG_DEBUG_NGIM, rev->log, 0,
                   "ngim http process request header line");

    if (c->destroyed) {
        return;
    }

    if (rev->timedout) {
        ngx_log_error(NGX_LOG_INFO, c->log, NGX_ETIMEDOUT, 
                      "client timed out");
        c->timedout = 1;
        ngx_ngim_finalize_session(s);
        return;
    }

    if (rev->timer_set) {
       ngx_del_timer(rev);
    }

    rc = NGX_AGAIN;

    for ( ;; ) {

        if (rc == NGX_AGAIN) {

            if (r->header_in->pos == r->header_in->end) {

                rv = ngx_ngim_http_alloc_large_header_buffer(r, 0);

                if (rv == NGX_ERROR) {
                    ngx_ngim_finalize_session(s);
                    return;
                }

                if (rv == NGX_DECLINED) {
                    p = r->header_name_start;

                    r->lingering_close = 1;

                    if (p == NULL) {
                        ngx_log_error(NGX_LOG_INFO, c->log, 0,
                                      "client sent too large request");
                        ngx_ngim_finalize_session(s);
                        return;
                    }

                    len = r->header_in->end - p;

                    if (len > NGX_MAX_ERROR_STR - 300) {
                        len = NGX_MAX_ERROR_STR - 300;
                        p[len++] = '.'; p[len++] = '.'; p[len++] = '.';
                    }

                    ngx_log_error(NGX_LOG_INFO, c->log, 0,
                                  "client sent too long header line: \"%*s\"",
                                  len, r->header_name_start);

                    ngx_ngim_finalize_session(s);
                    return;
                }
            }

            n = ngx_ngim_http_read_request_header(r,500);

            if (n == NGX_AGAIN || n == NGX_ERROR) {
                return;
            }
        }

        rc = ngx_http_parse_header_line(r, r->header_in,
                                        1);//cscf->underscores_in_headers);

        if (rc == NGX_OK) {

            if (r->invalid_header && 1 ){ //cscf->ignore_invalid_headers) 

                /* there was error while a header line parsing */

                ngx_log_error(NGX_LOG_INFO, c->log, 0,
                              "client sent invalid header line: \"%*s\"",
                              r->header_end - r->header_name_start,
                              r->header_name_start);
                continue;
            }

            /* a header line has been parsed successfully */

            h = ngx_list_push(&r->headers_in.headers);
            if (h == NULL) {
                ngx_ngim_finalize_session(s);
                return;
            }

            h->hash = r->header_hash;

            h->key.len = r->header_name_end - r->header_name_start;
            h->key.data = r->header_name_start;
            h->key.data[h->key.len] = '\0';

            h->value.len = r->header_end - r->header_start;
            h->value.data = r->header_start;
            h->value.data[h->value.len] = '\0';

            h->lowcase_key = ngx_pnalloc(r->pool, h->key.len);
            if (h->lowcase_key == NULL) {
                ngx_ngim_finalize_session(s);
                return;
            }

            if (h->key.len == r->lowcase_index) {
                ngx_memcpy(h->lowcase_key, r->lowcase_header, h->key.len);

            } else {
                ngx_strlow(h->lowcase_key, h->key.data, h->key.len);
            }

            /*hh = ngx_hash_find(&cmcf->headers_in_hash, h->hash,
                               h->lowcase_key, h->key.len);

            if (hh && hh->handler(r, h, hh->offset) != NGX_OK) {
                return;
            }*/

            ngx_log_debug2(NGX_LOG_DEBUG_NGIM, r->connection->log, 0,
                           "http header: \"%V: %V\"",
                           &h->key, &h->value);

            continue;
        }

        if (rc == NGX_HTTP_PARSE_HEADER_DONE) {

            /* a whole header has been parsed successfully */

            ngx_log_debug0(NGX_LOG_DEBUG_NGIM, r->connection->log, 0,
                           "http header done");

            r->request_length += r->header_in->pos - r->header_in->start;

            r->http_state = NGX_HTTP_PROCESS_REQUEST_STATE;

            /*rc = ngx_http_process_request_header(r);

            if (rc != NGX_OK) {
                return;
            }*/

            rev->handler = ngx_ngim_http_test_reading;

            s->name.data = r->uri.data+1;
            s->name.len  = r->uri.len-1;
            s->stage = NGX_NGIM_SESSION_PREPARE_REQUEST;
            ngx_ngim_run_session(s);
            
            return;
        }

        if (rc == NGX_AGAIN) {

            /* a header line parsing is still not complete */

            continue;
        }

        /* rc == NGX_HTTP_PARSE_INVALID_HEADER: "\r" is not followed by "\n" */

        ngx_log_error(NGX_LOG_INFO, c->log, 0,
                      "client sent invalid header line: \"%*s\\r...\"",
                      r->header_end - r->header_name_start,
                      r->header_name_start);

        ngx_ngim_finalize_session(s);
        return;
    }
}

static void
ngx_ngim_http_test_reading(ngx_event_t *rev)
{
    int                      n;
    char               	     buf[1];
    ngx_err_t                err;
    ngx_connection_t         *c;
    ngx_ngim_session_t       *s;

    c = rev->data;
    s = c->data;

    ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0, "ngim http test reading");

#if (NGX_HAVE_KQUEUE)

    if (ngx_event_flags & NGX_USE_KQUEUE_EVENT) {

        if (!rev->pending_eof) {
            return;
        }

        rev->eof = 1;
        c->error = 1;
        err = rev->kq_errno;

        goto closed;
    }

#endif

    n = recv(c->fd, buf, 1, MSG_PEEK);

    if (n == 0) {
        rev->eof = 1;
        c->error = 1;
        err = 0;

        goto closed;

    } else if (n == -1) {
        err = ngx_socket_errno;

        if (err != NGX_EAGAIN) {
            rev->eof = 1;
            c->error = 1;

            goto closed;
        }
    }

    /* aio does not call this handler */

    if ((ngx_event_flags & NGX_USE_LEVEL_EVENT) && rev->active) {

        if (ngx_del_event(rev, NGX_READ_EVENT, 0) != NGX_OK) {
            ngx_ngim_finalize_session(s);
        }
    }

    return;

closed:

    ngx_log_error(NGX_LOG_INFO, c->log, err,
                  "client prematurely closed connection");

    if (err) {
       rev->error = 1;
       ngx_ngim_finalize_session(s);
       return;
    }


    if(s->async){
       ngx_ngim_async_close_connection(c);
    }else{
       ngx_ngim_finalize_session(s);
    }
}
